import express, {Request, Response} from "express";
import multer from "multer";
import path from "path";
import fs from 'fs'
import {parseToken} from "../utils/jwt";
import {tokenParams} from "../../global";
const router = express.Router()

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname, `../public${req.url}`)) // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        // console.log('req', )
        const params = parseToken(req.headers[process.env.NODE_MANAGE_TOKEN as string] as string) as tokenParams
        const suffix = file.originalname.split('.')[file.originalname.split('.').length - 1]
        cb(null, `${params.userUID}.${suffix}`)
    }
})
const upload = multer({ storage: storage });

// 上传JSON文件
router.post('/calendar', upload.single('file'), async (req: Request, res: Response) => {
   if (req.file) {
       res.send({ code: 200, message: '上传成功', data: null })
   }
})

// 读取JSON文件中的数据
router.post('/data',  async (req: Request, res: Response) => {
    try {
        const params = parseToken(req.headers[process.env.NODE_MANAGE_TOKEN as string] as string) as tokenParams
        fs.access(path.resolve(__dirname, `../public/calendar/${params.userUID}.json`), (error) => {
            if (error) {
               res.send({ code: 200, message: '请求成功', data: [] })
            } else {
                const data = fs.readFileSync(path.resolve(__dirname, `../public/calendar/${params.userUID}.json`), 'utf8');
                const jsonData = JSON.parse(data);
                res.send({ code: 200, message: '请求成功', data: jsonData })
            }
        })
    } catch (e: any) {
        res.send({ code: 500, message: '异常', data: null })
    }
})

export default router
